from loguru import logger

from core.db_conn import get_db_connection


def init_db() -> None:
    """
    初始化数据库，创建必要的表
    :return: 
    """
    conn = get_db_connection()
    try:
        with conn.cursor() as cursor:
            cursor.execute(
                """
                CREATE TABLE IF NOT EXISTS lottery_meta
                (
                    id
                    INT
                    AUTO_INCREMENT
                    PRIMARY
                    KEY,
                    lottery_code
                    VARCHAR
                (
                    50
                ) NOT NULL UNIQUE,
                    lottery_name VARCHAR
                (
                    100
                ) NOT NULL,
                    table_name VARCHAR
                (
                    100
                ) NOT NULL UNIQUE,
                    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                    last_bet_no VARCHAR
                (
                    50
                ) COMMENT '最后记录的期号',
                    last_request_time DATETIME COMMENT '最后请求时间'
                    )
                """
            )
        conn.commit()
        logger.info("数据库元表初始化完成")
    except Exception as e:
        logger.error(f"数据库元表初始化失败: {e}")
    finally:
        if conn:
            conn.close()
